package com.starblink.login.editpersonalinfo.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.MediaUtils
import com.luck.picture.lib.utils.PictureFileUtils
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.login.databinding.ActivityEditPersonalInfoBinding
import com.starblink.login.editpersonalinfo.ui.SelectGetPictureModeDialog.Companion.BUNDLE_KEY_GET_PICTURE_MODE
import com.starblink.login.editpersonalinfo.ui.SelectGetPictureModeDialog.Companion.REQUEST_KEY_GET_PICTURE_MODE
import com.yalantis.ucrop.UCrop
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

/**
 * 编辑个人信息
 */
@Route(path = RoutePage.Login.EDIT_PERSONAL_INFO, extras = RoutePage.Extra.NEED_LOGIN)
class EditPersonalInfoActivity :
    BaseTVMActivity<ActivityEditPersonalInfoBinding, EditPersonalInfoVM>() {
    companion object {
        const val TAG = "dss"
        const val REQUEST_CODE_EDIT_USERNAME = 101 //编辑用户名
        const val REQUEST_CODE_EDIT_PERSONAL_PROFILE = 102 //编辑个人简介
    }

    override fun initViewBinding(): ActivityEditPersonalInfoBinding =
        ActivityEditPersonalInfoBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        setStatusBarBlackText()
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        // 初始化，控件绑定数据
        initUserInfo()

        viewBinding.layUserHead.click {
            // 编辑头像
            SelectGetPictureModeDialog()
                .show(this.supportFragmentManager, SelectGetPictureModeDialog::class.simpleName)
        }
        supportFragmentManager.setFragmentResultListener(
            REQUEST_KEY_GET_PICTURE_MODE,
            this
        ) { _, bundle ->
            val getPictureMode = bundle.getInt(BUNDLE_KEY_GET_PICTURE_MODE)
            SKLogger.e("dss", "getPictureMode=$getPictureMode")
            if (getPictureMode == SelectGetPictureModeDialog.GET_PICTURE_MODE_TAKE_PICTURE) {
                getPictureByTakePhoto()
            } else {
                getPictureBySystemGallery()
            }
        }

        viewBinding.layUserName.click {
            // 编辑用户名
            navigationTo(RoutePage.Login.EDIT_USERNAME, REQUEST_CODE_EDIT_USERNAME) {
                withString(LoginManager.KEY_USERNAME, viewBinding.tvUserName.text.toString())
            }
        }

        viewBinding.layPersonalProfile.click {
            // 编辑个人简介
            navigationTo(
                RoutePage.Login.EDIT_PERSONAL_PROFILE,
                REQUEST_CODE_EDIT_PERSONAL_PROFILE
            ) {
                withString(
                    LoginManager.KEY_PERSONAL_PROFILE,
                    viewBinding.tvPersonalProfile.text.toString()
                )
            }
        }
        viewBinding.btnBottom.click {
            viewModel.updatePersonalInfo(
                username = viewBinding.tvUserName.text.toString(),
                personalProfile = viewBinding.tvPersonalProfile.text.toString()
            )
        }
    }

    private fun initUserInfo(){
        ImageUtils.loadImage(
            mContext,
            UserDataCenter.getAccountInfo()?.headImage,
            viewBinding.ivUserHead,
            ImageUtils.placeholderAvatarImage,
            ImageUtils.placeholderAvatarImage
        )
        viewBinding.tvUserName.text = UserDataCenter.getAccountInfo()?.userName ?: ""
        viewBinding.tvPersonalProfile.text = UserDataCenter.getAccountInfo()?.description ?: ""
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.userInfoLiveData.observe(this){
            initUserInfo()
        }
    }

    override fun initLoad() {
        super.initLoad()
        viewModel.refreshUserInfo()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_EDIT_USERNAME -> {
                if (resultCode == Activity.RESULT_OK) {
                    // 设置新值
                    if (data?.getStringExtra(LoginManager.KEY_USERNAME).isNullOrEmpty().not()) {
                        viewBinding.tvUserName.text =
                            data?.getStringExtra(LoginManager.KEY_USERNAME)
                    }
                }
            }
            REQUEST_CODE_EDIT_PERSONAL_PROFILE -> {
                if (resultCode == Activity.RESULT_OK) {
                    // 设置新值
                    if (data?.hasExtra(LoginManager.KEY_PERSONAL_PROFILE) == true) {
                        YYLogUtils.e(
                            "KEY_PERSONAL_PROFILE=${data.getStringExtra(LoginManager.KEY_PERSONAL_PROFILE)}",
                            "dss"
                        )
                        viewBinding.tvPersonalProfile.text =
                            data.getStringExtra(LoginManager.KEY_PERSONAL_PROFILE)
                    }
                }
            }
        }
    }

    // 使用系统相机拍照
    fun getPictureByTakePhoto() {
        PictureSelector.create(this)
            .openCamera(SelectMimeType.ofImage())
            .setCropEngine(ImageFileCropEngine()) // 圆形裁剪
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (!result.isEmpty()) {
                        SKLogger.e(TAG, "TakePhoto=${result[0].availablePath}")
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    SKLogger.i(TAG, "PictureSelector Cancel")
                }
            })
    }

    // 从系统相册选择
    fun getPictureBySystemGallery() {
        PictureSelector.create(this)
            .openSystemGallery(SelectMimeType.ofImage()) //从系统相册选图
            .setSelectionMode(SelectModeConfig.SINGLE) //单选
            .setCropEngine(ImageFileCropEngine()) // 圆形裁剪
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .setSkipCropMimeType(PictureMimeType.ofGIF(), PictureMimeType.ofWEBP()) //跳过不需要裁剪的类型
//                .setCustomLoadingListener(getCustomLoadingListener())
            .forSystemResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (!result.isEmpty()) {
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    SKLogger.i(TAG, "PictureSelector Cancel")
                }
            })
    }

    /**
     * 处理已选择的图片
     */
    fun handleSelectedPicture(image: String) {
        SKLogger.e("dss", "onImageSelect=$image")
        viewModel.newHeadImage = image
        viewModel.newHeadImageUrl = null

        ImageUtils.loadImage(
            mContext,
            image,
            viewBinding.ivUserHead,
            ImageUtils.placeholderAvatarImage,
            ImageUtils.placeholderAvatarImage
        )
    }


/**
 * 自定义压缩
 */
private class ImageFileCompressEngine : CompressFileEngine {
    override fun onStartCompress(
        context: Context,
        source: java.util.ArrayList<Uri>,
        call: OnKeyValueResultCallbackListener
    ) {
        Luban.with(context).load(source)
            .setRenameListener { filePath ->
                // 设置压缩后的文件名
                val indexOf = filePath.lastIndexOf(".")
                val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                DateUtils.getCreateFileName("CMP_") + postfix
            }.filter { path ->
                // 仅压缩图片，Gif跳过
                if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                    true
                } else {
                    !PictureMimeType.isUrlHasGif(path)
                }
            }.setCompressListener(object : OnNewCompressListener {
                override fun onStart() {}
                override fun onSuccess(source: String, compressFile: File) {
                    if (call != null) {
                        call.onCallback(source, compressFile.absolutePath)
                    }
                }

                override fun onError(source: String, e: Throwable?) {
                    if (call != null) {
                        call.onCallback(source, null)
                    }
                }
            }).launch()
    }
}

/**
 * 自定义裁剪
 */
private class ImageFileCropEngine : CropFileEngine {
    override fun onStartCrop(
        fragment: Fragment,
        srcUri: Uri,
        destinationUri: Uri,
        dataSource: java.util.ArrayList<String>,
        requestCode: Int
    ) {
        SKLogger.e("dss", "onStartCrop")
        val options = buildOptions()
        val uCrop = UCrop.of(srcUri, destinationUri, dataSource)
        uCrop.withOptions(options)
        uCrop.start(fragment.requireActivity(), fragment, requestCode)
    }

    /**
     * 配制UCrop
     */
    private fun buildOptions(): UCrop.Options {
        val options = UCrop.Options()
        options.setCircleDimmedLayer(true) // 圆形头像裁剪模式
        options.setHideBottomControls(true)  //是否显示底部菜单栏,默认显示（设置缩放比例和旋转）
        options.setFreeStyleCropEnabled(false) //true-显示裁剪框，拖动裁剪框；false-拖动图片；默认false
        options.setShowCropFrame(false) //是否显示裁剪边框
        options.setShowCropGrid(false) //是否显示裁剪框网格
//            options.setMaxScaleMultiplier(100f)//设置图片最大缩放倍数
        options.setStatusBarColor(CommUtils.getColor(com.starblink.basic.style.R.color.black)) //设置状态栏颜色
        options.setToolbarColor(CommUtils.getColor(com.starblink.basic.style.R.color.black)) //设置标题栏颜色
        options.setCircleStrokeWidth(0.5.dp)
        options.setCircleStrokeColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray5))
        options.setToolbarWidgetColor(CommUtils.getColor(com.starblink.basic.style.R.color.white))
        options.setToolbarCancelDrawable(com.starblink.basic.style.R.drawable.bar_arrows_left_white)
        options.setToolbarTitle("")

        return options
    }
}

/**
 * 处理选择结果
 *
 * @param result
 */
private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
    if (result == null) return
    for (media in result) {
        if (media.width == 0 || media.height == 0) {
            if (PictureMimeType.isHasImage(media.mimeType)) {
                val imageExtraInfo = MediaUtils.getImageSize(commContext(), media.path)
                media.width = imageExtraInfo.width
                media.height = imageExtraInfo.height
            } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                val videoExtraInfo = MediaUtils.getVideoSize(commContext(), media.path)
                media.width = videoExtraInfo.width
                media.height = videoExtraInfo.height
            }
        }
        SKLogger.i(TAG, "文件名: " + media.fileName)
        SKLogger.i(TAG, "是否压缩:" + media.isCompressed)
        SKLogger.i(TAG, "压缩:" + media.compressPath)
        SKLogger.i(TAG, "初始路径:" + media.path)
        SKLogger.i(TAG, "绝对路径:" + media.realPath)
        SKLogger.i(TAG, "是否裁剪:" + media.isCut)
        SKLogger.i(TAG, "裁剪路径:" + media.cutPath)
        SKLogger.i(TAG, "是否开启原图:" + media.isOriginal)
        SKLogger.i(TAG, "原图路径:" + media.originalPath)
        SKLogger.i(TAG, "沙盒路径:" + media.sandboxPath)
        SKLogger.i(TAG, "水印路径:" + media.watermarkPath)
        SKLogger.i(TAG, "视频缩略图:" + media.videoThumbnailPath)
        SKLogger.i(TAG, "原始宽高: " + media.width + "x" + media.height)
        SKLogger.i(TAG, "裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
        SKLogger.i(
            TAG,
            "文件大小: " + PictureFileUtils.formatAccurateUnitFileSize(media.size)
        )
        SKLogger.i(TAG, "文件时长: " + media.duration)
    }
}

}